package top.lyc829.iot_android.fragment.profile.nfc;

import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.SPUtils;
import com.gturedi.views.StatefulLayout;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xhttp2.model.ApiResult;
import com.xuexiang.xhttp2.request.CustomRequest;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import top.lyc829.iot_android.R;
import top.lyc829.iot_android.adapter.FingerAdapter;
import top.lyc829.iot_android.adapter.NfcAdapter;
import top.lyc829.iot_android.core.BaseFragment;
import top.lyc829.iot_android.entity.Finger;
import top.lyc829.iot_android.entity.User;
import top.lyc829.iot_android.http.service.UserService;
import top.lyc829.iot_android.http.subscriber.NoTipRequestSubscriber;
import top.lyc829.iot_android.http.subscriber.TipProgressLoadingSubscriber;
import top.lyc829.iot_android.util.Utils;

@Page(name = "NfcFragment")
public class NfcFragment extends BaseFragment {

    @BindView(R.id.nfc_recyclerview)
    RecyclerView mRecyclerView;
    @BindView(R.id.ll_stateful)
    StatefulLayout mLlStateful;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;

    private NfcAdapter adapter;


    @Override
    protected TitleBar initTitle() {
        TitleBar titleBar = super.initTitle()
                .setTitle("卡片");
        titleBar.addAction(new TitleBar.TextAction("添加卡片") {
            @Override
            public void performAction(View view) {
                addNfc();
            }
        });
        return titleBar;
    }


    public static NfcFragment newInstance() {
        return new NfcFragment();
    }


    @Override
    protected int getLayoutId() {
        return R.layout.nfc_fragment;
    }

    @Override
    protected void initViews() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setAdapter(adapter = new NfcAdapter());
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    }

    @Override
    protected void initListeners() {
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final @NonNull RefreshLayout refreshLayout) {
                mLlStateful.showLoading();
                getNfcList(refreshLayout);
            }
        });
        mRefreshLayout.autoRefresh();

        adapter.setOnItemClickListener((adapter1, view, position) -> {
            new MaterialDialog.Builder(getContext())
                    .title("提示")
                    .content("是否删除卡片?")
                    .positiveText("确定")
                    .negativeText("取消")
                    .onPositive((dialog, which) -> {
                        deleteNfc(position);
                    })
                    .show();
        });

    }


    private void getNfcList(RefreshLayout refreshLayout) {
        CustomRequest request = XHttp.custom();

        request.apiCall(request.create(UserService.class).getNfcs(Integer.parseInt(SPUtils.getInstance().getString("token"))))
                .subscribeWith(new NoTipRequestSubscriber<User>() {
                    @Override
                    protected void onSuccess(User user) {
                        List<User> users = new ArrayList<>();
                        if (user == null || Utils.isStringEmpty(user.getNfcId())) {
                            mLlStateful.showEmpty();
                        } else {
                            mLlStateful.showContent();
                            users.add(user);
                        }
                        refreshLayout.finishRefresh(true);
                        adapter.setList(users);
                    }

                    @Override
                    public void onError(ApiException e) {
                        refreshLayout.finishRefresh(true);
                        mLlStateful.showError(e.getMessage(), v -> {
                            getNfcList(refreshLayout);
                        });
                    }
                });
    }

    private void addNfc() {
        if (adapter.getData().size() > 0) {
            Utils.showToast("暂时只能添加一张卡片, 请删除后再添加");
            return;
        }


        CustomRequest request = XHttp.custom();
        request.call(request.create(UserService.class)
                .addNfc(Integer.parseInt(SPUtils.getInstance().getString("token", "-1"))))
                .subscribeWith(new TipProgressLoadingSubscriber<ApiResult>(getProgressLoader()) {
                    @Override
                    protected void onSuccess(ApiResult apiResult) {
                        if (apiResult.isSuccess()) {
                            Utils.showToast("请前往刷卡机添加卡片");
                        } else {
                            Utils.showToast(apiResult.getMsg());
                        }

                    }
                });


    }

    private void deleteNfc(int position) {
        CustomRequest request = XHttp.custom();
        request.call(request.create(UserService.class).deleteNfc(adapter.getItem(position)))
                .subscribeWith(new TipProgressLoadingSubscriber<ApiResult>(getProgressLoader()) {
                    @Override
                    protected void onSuccess(ApiResult apiResult) {
                        if (apiResult.isSuccess()) {
                            adapter.removeAt(position);
                            if (adapter.getData().size() == 0) {
                                mLlStateful.showEmpty();
                            }

                        } else {
                            Utils.showToast(apiResult.getMsg());
                        }

                    }
                });


    }


}